<template>
  <n-grid :cols="12">
    <n-grid-item :offset="2" span="8">
      <detail-page-header title="检查清单详情"> </detail-page-header>
      <div class="mt-[16px]">
        <n-card>
          <n-spin :show="initLoading">
            <n-form ref="formRef" :model="checkListForm">
              <n-grid :cols="24" x-gap="10" y-gap="10">
                <n-grid-item :span="24">
                  <n-form-item label="检查清单名称" path="name">
                    <n-input
                      v-model:value="checkListForm.name"
                      placeholder="请输入检查清单名称"
                    />
                  </n-form-item>
                </n-grid-item>
                <n-grid-item :span="24">
                  <n-form-item label="关联产品" path="productId">
                    <n-select
                      :options="productOpts"
                      v-model:value="checkListForm.productId"
                      value-field="id"
                      label-field="name"
                      placeholder="请选择关联产品"
                      remote
                      clearable
                      filterable
                      @search="handleSearchProduct"
                    />
                  </n-form-item>
                </n-grid-item>
                <template
                  v-for="(item, $index) in shownQuestionList"
                  :key="item.id"
                >
                  <n-grid-item :span="24">
                    <n-divider />
                  </n-grid-item>
                  <n-grid-item
                    :span="24"
                    v-if="shownQuestionList && shownQuestionList.length > 1"
                  >
                    <div class="text-right">
                      <n-button
                        size="small"
                        type="error"
                        secondary
                        @click="handleRemoveQuestion(item)"
                      >
                        <template #icon>
                          <Trash />
                        </template>
                      </n-button>
                    </div>
                  </n-grid-item>
                  <n-grid-item :span="20">
                    <n-form-item :label="`检查项${$index + 1}`">
                      <n-input
                        v-model:value="item.name"
                        placeholder="请输入检查项"
                      />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item :span="4">
                    <n-form-item :show-lable="false">
                      <n-checkbox
                        v-model:checked="item.showRepair"
                        :checked-value="'1'"
                        :unchecked-value="'0'"
                      >
                        维修是否适用
                      </n-checkbox>
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item :span="24">
                    <n-form-item label="详细描述">
                      <n-input
                        v-model:value="item.description"
                        type="textarea"
                        placeholder="请输入详细描述"
                      />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item :span="24">
                    <n-form-item label="关联零部件">
                      <n-select
                        v-model:value="item.variantId"
                        :options="variantOpts"
                        placeholder="请选择关联零部件"
                        value-field="id"
                        label-field="name"
                        remote
                        clearable
                        filterable
                        @search="handleSearchVariants"
                      />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item :span="8">
                    <n-form-item label="回收扣减金额">
                      <n-input-number
                        class="w-full"
                        v-model:value="item.tradeinReducePrice"
                      />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item :span="8">
                    <n-form-item label="维修服务费">
                      <n-input-number
                        class="w-full"
                        v-model:value="item.repairPrice"
                      />
                    </n-form-item>
                  </n-grid-item>
                  <n-grid-item :span="8">
                    <n-form-item label="维修费用">
                      <n-input-number
                        class="w-full"
                        v-model:value="item.repairPromoPrice"
                      />
                    </n-form-item>
                  </n-grid-item>
                </template>
                <n-grid-item :span="24">
                  <n-button
                    block
                    tertiary
                    type="primary"
                    @click.stop="handleAddQuestion"
                  >
                    <template #icon>
                      <AddCircleOutline />
                    </template>
                    添加检查项
                  </n-button>
                </n-grid-item>

                <n-grid-item :span="24">
                  <div class="text-right pt-4">
                    <n-button
                      type="primary"
                      :loading="submitLoading"
                      @click.stop="handleSubmit"
                    >
                      保存
                    </n-button>
                  </div>
                </n-grid-item>
              </n-grid>
            </n-form>
          </n-spin>
        </n-card>
      </div>
    </n-grid-item>
  </n-grid>
</template>
<script setup lang="ts">
import { onMounted, ref, reactive, computed } from "vue";
import { cloneDeep, get, debounce } from "lodash-es";
import { AddCircleOutline, Trash } from "@vicons/ionicons5";
import { ICheckListDetailProps } from "./props";
import {
  getCheckListDetailById,
  updateCheckList,
} from "@/api/checkList/checkList.api";
import {
  CheckListDto,
  QuestionItem,
} from "@/types/model/checkList/dtos/checkList.dto";
import { ActionTypeEnum } from "@/enums/actionTypeEnum";
import { useCheckListAction } from "../hooks/useCheckListAction";

const props = defineProps<ICheckListDetailProps>();

const {
  productOpts,
  variantOpts,
  handleSearchProduct,
  handleSearchVariants,
  addQuestionItem,
} = useCheckListAction();

const initLoading = ref<boolean>(true);
const submitLoading = ref<boolean>(false);
const checkListDetail = ref<any>({});

const checkListForm = reactive<CheckListDto>({
  id: "",
  name: "",
  productId: undefined,
  questionList: [],
});

const shownQuestionList = computed(() => {
  let questions: QuestionItem[] = [];
  if (checkListForm.questionList.length) {
    questions = checkListForm.questionList.filter(
      (item: QuestionItem) => item.actionType !== ActionTypeEnum.REMOVE
    );
  }
  return questions;
});

const handleGetCheckListDetail = async (id: string) => {
  initLoading.value = true;
  const result = await getCheckListDetailById(id);
  console.log(result);
  const _checkListDetail = get(result, "result") || {};
  checkListForm.id = _checkListDetail.id;
  checkListForm.name = _checkListDetail.name;
  checkListForm.productId = _checkListDetail.productId;
  productOpts.value = [
    {
      id: _checkListDetail.productId,
      name: _checkListDetail.productName,
    },
  ];
  const _questionList: QuestionItem[] = [];
  const _variantOpts: any[] = [];

  _checkListDetail.questionItems.forEach((item: QuestionItem) => {
    _questionList.push({
      ...item,
      actionType: ActionTypeEnum.EDIT,
    });
    _variantOpts.push({
      id: item.variantId,
      name: item.variantName,
    });
  });

  checkListForm.questionList = _questionList;

  variantOpts.value = _variantOpts;

  checkListDetail.value = cloneDeep(_checkListDetail);
  initLoading.value = false;
};

const handleAddQuestion = () => {
  checkListForm.questionList.push(addQuestionItem());
};

const handleRemoveQuestion = (question: QuestionItem) => {
  if (question.id) {
    const _actionType = get(question, "actionType") || "";
    if (_actionType === ActionTypeEnum.EDIT) {
      question.actionType = ActionTypeEnum.REMOVE;
    } else {
      checkListForm.questionList = checkListForm.questionList.filter(
        (item: QuestionItem) => item.id !== question.id
      );
    }
  }
};

const handleSubmit = debounce(async function () {
  console.log(checkListForm);
  submitLoading.value = true;
  try {
    const res = await updateCheckList(checkListForm);
    console.log(res);
  } finally {
    submitLoading.value = false;
  }
}, 500);

const init = () => {
  handleGetCheckListDetail(props.id);
};

onMounted(() => {
  init();
});
</script>
